﻿using System;
using System.Collections.Generic;
using FairyGUI;
using UnityEngine;
public class FEditSuitMediator : MyWindow
{
    GTextField _idText;
    GTextInput _nameEditBox;
    Controller _selectProCtrl;
    Controller _levelControl;
    GList _selectPropertyBtnList;
    GList _selectPropertyList;
    GList _showPropertyList;
    GList _equipmentList;
    GButton _randPropertyBtn;

    List<SkillBase> _levelSkillList;
    List<PropertyValue<object>> _hasPropertyList;
    List<Weapon> _weaponList;

    Suit _suitData = null;
    Suit _preSuitData = null;
    int _suitIndex;

    public FEditSuitMediator()
    {
        this.contentPane = UIPackage.CreateObject("EquipmentPackage", "EditSuitPanel").asCom;
        //组件获取
        _idText = this.contentPane.GetChild("idText").asTextField;
        _nameEditBox = this.contentPane.GetChild("nameEditBox").asTextInput;
        _showPropertyList = this.contentPane.GetChild("showPropertyList").asList;
        _selectPropertyList = this.contentPane.GetChild("selectPropertyList").asList;
        _selectPropertyBtnList = this.contentPane.GetChild("selectPropertyBtnList").asList;
        _equipmentList = this.contentPane.GetChild("equipmentList").asList;
        _levelControl = this.contentPane.GetController("LevelControl");
        _selectProCtrl = this.contentPane.GetController("SelectProCtrl");
        _randPropertyBtn = this.contentPane.GetChild("randPropertyBtn").asButton;

        //按钮事件监听
        this.contentPane.GetChild("exitBtn").onClick.Add(OnExitPanel);
        this.contentPane.GetChild("saveBtn").onClick.Add(OnSaveBtnClick);
        this.contentPane.GetChild("delBtn").onClick.Add(OnDelBtnClick);
        this.contentPane.GetChild("addWeaponBtn").onClick.Add(OnAddWeaponBtnClick);
        _randPropertyBtn.onClick.Add(OnRandPropertyBtnClick);
        //控制器
        _levelControl.onChanged.Add(OnLevelCtrlChange);
        _selectProCtrl.onChanged.Add(OnSelectProCtrlChange);
        //文本
        _nameEditBox.onFocusOut.Add(OnNameEditBoxOut);
        //列表
        _showPropertyList.itemRenderer = RenderListItem;
        _selectPropertyBtnList.itemRenderer = RenderBtnListItem;
        _selectPropertyList.itemRenderer = RenderSelectPropertyListItem;
        _equipmentList.itemRenderer = RenderEquipmentListItem;
        _selectPropertyList.onClickItem.Add(OnSelectPropertyListClick);
    }

    protected override void OnInit()
    {
        base.OnInit();
        this.Center();
    }
    /// <summary>
    /// 编写其他需要在窗口显示时处理的业务逻辑。
    /// </summary>
    protected override void OnShown()
    {
        base.OnShown();
 
    }
    public void InitData(Suit suit,int suitIndex)
    {
        CheckDataChange(() => {
            ResetPanel();
            _preSuitData = suit;
            _suitData = suit.DeepClone();
            _suitIndex = suitIndex;

            _idText.text = _suitData.id;
            _nameEditBox.text = _suitData.GetSuitName();
            _randPropertyBtn.selected = _suitData.randProperty.isRand == 1;
            FresSelecthPropertyPanel();
        });
    }
    /// <summary>
    /// 重置面板
    /// </summary>
    private void ResetPanel(){

    }
    /// <summary>
    /// 刷新属性操作面板
    /// </summary>
    private void FresSelecthPropertyPanel()
    {
        //清除数据
        _selectProCtrl.ClearPages();
        _selectPropertyBtnList.RemoveChildrenToPool();
        _showPropertyList.RemoveChildrenToPool();
        //赋给全局变量，方便使用
        _levelSkillList = _suitData.numProperty;

        var levelSkill = GetLevelSkill();
        for (int i = 0; i < levelSkill.propertyList.Count; i++)
        {
            _selectProCtrl.AddPage("page_" + i);
        }
        //1级 如果本来就是0，则手动调用变化
        if(_levelControl.selectedIndex == 0) OnLevelCtrlChange(null);
        _levelControl.selectedIndex = 0;
        //在控制器页面生成完后再渲染
        _selectPropertyBtnList.numItems = levelSkill.propertyList.Count;
        //需要选项
        _selectProCtrl.selectedIndex = 0;

        _weaponList = new List<Weapon>();
        foreach(var item in _suitData.weaponList){
            var weapon = WeaponMO.GetWeaponById(item);
            if(weapon != null) _weaponList.Add(weapon);
        }
        _equipmentList.RemoveChildrenToPool();
        _equipmentList.numItems = _weaponList.Count;
    }
    /// <summary>
    /// 已选择的属性列表
    /// </summary>
    /// <param name="index"></param>
    /// <param name="item"></param>
    void RenderListItem(int index, GObject item)
    {
        //如果为空则重新拿值
        if(_hasPropertyList == null) GetHasPropertyList();
        var _item = item.asCom;
        _item.GetChild("showPropertybtn").onClick.Add(OnShowPropertyListModifyClick);
        _item.GetChild("closePropertyBtn").onClick.Add(OnShowPropertyListCloseClick);
        _item.GetChild("showPropertybtn").asButton.title = _hasPropertyList[index].GetDiscript();
    }
    /// <summary>
    /// 选择属性分类按钮列表
    /// </summary>
    /// <param name="index"></param>
    /// <param name="item"></param>
    void RenderBtnListItem(int index, GObject item)
    {
        var levelSkill = GetLevelSkill();
        item.asCom.GetChild("title").asTextField.text = levelSkill.propertyList[index].GetDiscript(false); 
    }
    /// <summary>
    /// 供选择的属性列表
    /// </summary>
    /// <param name="index"></param>
    /// <param name="item"></param>
    void RenderSelectPropertyListItem(int index, GObject item)
    {
        var property = GetLevelProperty();
        var propertyList = property.val.propertyList;
        item.asCom.GetChild("title").asTextField.text = propertyList[index].GetDiscript(false);
    }
    /// <summary>
    /// 编写其他需要在窗口隐藏时处理的业务逻辑。
    /// </summary>
    protected override void OnHide()
    {
        base.OnHide();
    }
    private void OnExitPanel()
    {
        CheckDataChange(() => {
            _suitData.ActiveRandProperty();
            _preSuitData = null;
            this.Hide();
        });
    }
    private void CheckDataChange(ZeroDeletegate cb){
        if(_preSuitData == null) {
            cb();
            return;
        }
        var isEqual = Utils.CompareObject(_preSuitData,_suitData);
        var isChange = this.TextIsChange(false);
        //判断是否有改变
        if(!isEqual || isChange){
            FUIMain.TipPanel("套装数据发生改变，确定放弃本次修改？", (status) => {
                if ((int)status == 1)
                {
                    cb();
                }
            });
        }else{
            cb();
        }
    }
    /// <summary>
    /// 判断文字是否发生改变
    /// </summary>
    /// <returns></returns>
    private bool TextIsChange(bool isSave = true){
        var isChange = false;
        //判断是否需要重新保存名字
        if(_preSuitData.GetSuitName() != _nameEditBox.text)
        {
            if(isSave) LTLocalization.AddText(_preSuitData.name, _nameEditBox.text);
            isChange = true;
        }
        return isChange;
    }
    /// <summary>
    /// 刷新已有属性显示面板
    /// </summary>
    /// <param name="count"></param>
    private void FreshShowPropertyList(int count)
    {
        _showPropertyList.RemoveChildrenToPool();
        _showPropertyList.numItems = count;
    }
    /// <summary>
    /// 等级控制器
    /// </summary>
    /// <param name="context"></param>
    private void OnLevelCtrlChange(EventContext context)
    {
        if (_levelControl.selectedIndex < 0) return;
        Debug.Log("OnLevelCtrlChange" + _levelControl.selectedIndex);
        //更新已有属性
        FreshShowPropertyList(GetHasPropertyList().Count);
    }
    /// <summary>
    /// 属性分类变化控制器
    /// </summary>
    /// <param name="context"></param>
    private void OnSelectProCtrlChange(EventContext context)
    {
        var _ctrl = (Controller)context.sender;
        if (_ctrl.selectedIndex < 0) return;
 
        Debug.Log("OnSelectProCtrlChange" + _ctrl.selectedIndex);
        _selectPropertyList.RemoveChildrenToPool();
        var property = GetLevelProperty();
        var propertyList = property.val.propertyList;
        _selectPropertyList.numItems = propertyList.Count;
    }
    /// <summary>
    /// 选择某一个属性
    /// </summary>
    /// <param name="context"></param>
    private void OnSelectPropertyListClick(EventContext context)
    {
        var index = _selectPropertyList.GetChildIndex((GObject)context.data);
        var property = GetLevelProperty();

        var descript = property.val.propertyList[index].GetDiscript(false);
        int num = Utils.GetCharNums(descript, @"\?");
        string str = "";
        for(int i = 0;i < num - 1; i++)
        {
            str += "-";
        }
        //不需要输入的
        if(num == 0)
        {
            property.val.propertyList[index].val = 1;
            FreshShowPropertyList(GetHasPropertyList().Count);
            Debug.Log("index:" + index + "count:" + _showPropertyList.numItems);
        }
        else
        {
            //如果已经有值，则修改
            if (property.val.propertyList[index].val.ToString() != "0") str = property.val.propertyList[index].val.ToString();
            FUIMain.InputPanel(str,(status,val) => {
                if((int)status == 1)
                {
                    property.val.propertyList[index].val = val;
                    FreshShowPropertyList(GetHasPropertyList().Count);
                }
            });
        }
    }
    /// <summary>
    /// 选择删除已有的某一个属性
    /// </summary>
    /// <param name="context"></param>
    private void OnShowPropertyListCloseClick(EventContext context)
    {
        var index = _showPropertyList.GetChildIndex(((GObject)context.sender).parent);
        _hasPropertyList[index].val = 0;
        _hasPropertyList.RemoveAt(index);
        FreshShowPropertyList(_hasPropertyList.Count);
        Debug.Log("close index:" + index + "count:" + _showPropertyList.numItems);
    }
    /// <summary>
    /// 选择修改已有的某一个属性
    /// </summary>
    /// <param name="context"></param>
    private void OnShowPropertyListModifyClick(EventContext context)
    {
        var index = _showPropertyList.GetChildIndex(((GObject)context.sender).parent);
        var descript = _hasPropertyList[index].GetDiscript(false);
        int num = Utils.GetCharNums(descript, @"\?");
        //没有?就不需要修改
        if (num == 0) return;
        FUIMain.InputPanel(_hasPropertyList[index].val.ToString(), (status,val) => {
            if((int)status == 1)
            {
                _hasPropertyList[index].val = val;
                FreshShowPropertyList(_hasPropertyList.Count);
            }
        });
        Debug.Log("modify index:" + index + "count:" + _showPropertyList.numItems);
    }
    private void RenderEquipmentListItem(int index, GObject item)
    {
        item.text = _weaponList[index].GetWeaponName();
        item.asCom.GetChild("removeBtn").onClick.Add(OnRemoveWeaponBtn);
        item.asCom.GetChild("title").onClick.Add(OnEditWeaponClick);
    }
    private void OnRemoveWeaponBtn(EventContext context)
    {
        var index = _equipmentList.GetChildIndex(((GObject)context.sender).parent);
        _suitData.RemoveWeapon(_weaponList[index].id);
        _weaponList.RemoveAt(index);
        // _equipmentList.RemoveChildrenToPool();
        _equipmentList.RemoveChildToPoolAt(index);
    }

    private void OnEditWeaponClick(EventContext context)
    {
        var panel = (FEditWeaponMediator)FUIMain.ShowPanel(GMConfig.PanelType.EditWeaponPanel);
        var index = _equipmentList.GetChildIndex(((GObject)context.sender).parent);
        panel.InitData(_weaponList[index],WeaponMO.GetWeaponIndex(_weaponList[index]));
    }
    private void OnAddWeaponBtnClick(EventContext context)
    {
        FUIMain.ShowPanel(GMConfig.PanelType.SelectWeaponList,(res) => {
            FUIMain.ClosePanel(GMConfig.PanelType.SelectWeaponList);
            if(res != null) {
                _suitData.AddWeapon(res.ToString());
                var weapon = WeaponMO.GetWeaponById(res.ToString());
                if(weapon != null && !_weaponList.Contains(weapon)){
                    _weaponList.Add(weapon);
                    var item = _equipmentList.AddItemFromPool();
                    RenderEquipmentListItem(_weaponList.Count - 1,item);
                }
            }
        });
    }
    /// <summary>
    /// 技能类型变化
    /// </summary>
    private void OnNameEditBoxOut()
    {
        Debug.Log(_nameEditBox.text);
        Debug.Log(_suitData.name);
    }
    /// <summary>
    /// 随机属性按钮点击
    /// </summary>
    /// <param name="context"></param>
    private void OnRandPropertyBtnClick(EventContext context)
    {
        _suitData.randProperty.isRand = _randPropertyBtn.selected ? 1 : 0;
    }
    /// <summary>
    /// 保存套装数据
    /// </summary>
    private void OnSaveBtnClick()
    {
        //判断是否需要重新保存名字
        var isChange = this.TextIsChange();
        if(isChange) LTLocalization.SaveDataToCSV();
        _preSuitData = _suitData.DeepClone();
        var isOk = FSuitListMediator.SaveSuit(_preSuitData,_suitIndex);
        var str = "保存成功！";
        if(!isOk) str = "保存失败！";
        FUIMain.TipPanel(str);
    }
    /// <summary>
    /// 保存套装数据
    /// </summary>
    private void OnDelBtnClick()
    {
        FUIMain.TipPanel("确定要删除本张套装？", (status) => {
            if ((int)status == 1)
            {
                FSuitListMediator.DelSuit(_suitIndex);
                _preSuitData = null;
                this.Hide();
            }
        });
    }
    /// <summary>
    /// 获得具体等级的属性列表
    /// </summary>
    /// <returns></returns>
    private SkillBase GetLevelSkill()
    {
        return (SkillBase)_levelSkillList[_levelControl.selectedIndex];
    }
    /// <summary>
    /// 获得分类中的具体属性
    /// </summary>
    /// <returns></returns>
    private PropertyValue<PropertyBase> GetLevelProperty()
    {
        var levelSkill = GetLevelSkill();
        var property = (PropertyValue<PropertyBase>)levelSkill.propertyList[_selectProCtrl.selectedIndex];
        return property;
    }
    private List<PropertyValue<object>> GetHasPropertyList()
    {
        _hasPropertyList = _suitData.GetHasPropertyList(_levelControl.selectedIndex);
        return _hasPropertyList;
    }
}

